import numpy as np
import pymongo


class Mongo:
    port = 2717
    host = '59.56.77.23'
    client = None
    db_name = 'openapi'

    def __init__(self):
        self.client = pymongo.MongoClient(host=self.host, port=self.port)

   # 更新功能
    def update_pro_score(self, pro_info):
        table_name = 'pro_info'
        db = self.client[self.db_name]
        collist = db.list_collection_names()
        if table_name in collist:  # 判断 sites 集合是否存在
            db[table_name].drop()
        pro = db[table_name]
        pro.insert_many(pro_info.to_dict("records_info"))

    # 实现分页
    def info_page_number(self, n, pagesize, user_id):
        table_name = 'rank_info'
        db = self.client[self.db_name]
        res = []
        count = 0
        for i in db[table_name].find({"user_id": {"$regex": user_id}}):
            count = count + 1
        for i in db[table_name].find({"user_id": {"$regex": user_id}}).skip(pagesize * (n - 1)).limit(pagesize):
            res.append({
                "user_id": i['user_id'],
                "accepted": i['solved'],
                "submit": i['submit'],
                "rank": i['rank']
            })
        return {"data": res, "sum": count}
	# 更新功能
    def rec_pro(self, user_id):
        table_name = 'rank_info'
        db = self.client[self.db_name]
        query = {"user_id": user_id}
        return db[table_name].find_one(query)['rec']

